<template>
  <!--Dialog-->
  <Dialog v-model="modelValue">
    <el-form :status-icon="true" :inline="true" :model="addForm" label-width="auto" ref="addFormRef">
      <el-row>
        <el-col :span="12">
          <el-form-item label="上级代理" prop="parentId">
            <AgentSelect v-model="addForm.parentId" @change="onsetSelectedNode" class="form-item-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="displayName" :rules="[{ required: true, message: '请输入代理商名称' }]">
            <el-input v-model="addForm.displayName" placeholder="请输入代理商名称" maxlength="256" class="form-item-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="isEnabled" :rules="[{ required: true, message: '请选择是否启用' }]">
            <el-switch v-model="addForm.isEnabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道类型" prop="parentId">
            <el-select v-model="addForm.channelType" clearable placeholder="请选择渠道类型" class="form-item-input">
              <el-option v-for="item in channelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道代理号" prop="displayName">
            <el-input v-model="addForm.displayName" placeholder="请输入代理商名称" maxlength="256" class="form-item-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道请求密匙" prop="displayName">
            <el-input v-model="addForm.displayName" placeholder="请输入代理商名称" maxlength="256" class="form-item-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道回调密匙" prop="displayName">
            <el-input v-model="addForm.displayName" placeholder="请输入代理商名称" maxlength="256" class="form-item-input" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="displayName" class="form-item-remark">
            <el-input type="textarea" :rows="4" v-model="addForm.displayName" placeholder="请输入备注" maxlength="1024" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSavue(addFormRef)" :loading="isLoading">保存</el-button>
      <el-button @click="onClose">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { AgentSelect } from '../../select/index';
import { createAsync } from '@/utils/api/organization/index';
import { Dialog } from '@/components/dialog/index';
import { propTypes } from '@/utils/propTypes';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { ValidateFieldsError } from 'async-validator/dist-types';
import type { AgentCreateDto } from '@/utils/api/agent/type';

// 渠道类型数据
const channelTypeOptions = [
  {
    value: '1',
    label: '乐刷',
  },
  {
    value: '2',
    label: '随行付',
  },
  {
    value: '3',
    label: '新利建行',
  }
];

// 定义emits
const emits = defineEmits<{
  (e: 'update:refresh'): void;
}>();

// 刷新父组件
const refresh = () => {
  emits('update:refresh');
};

// 组织选择后的业务逻辑
const onsetSelectedNode = (val: any) => {
  addForm.value.parentId = val[val.length - 1];
};

// 控制组件隐藏与显示
const modelValue = defineModel<boolean>(propTypes.bool.def(false));
const close = () => {
  modelValue.value = false;
};
// 保存Loading效果状态
const isLoading = ref<boolean>(false);

// 关闭
const onClose = () => {
  //触发自定义事件
  close();
};

// 保存
const onSavue = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) {
    return;
  }

  // 提交验证
  await formEl.validate(
    async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
      if (isValid) {
        try {
          isLoading.value = true;

          await createAsync(addForm.value);

          // 关闭弹窗
          close();

          // 提示成功
          ElMessage({
            showClose: true,
            message: '添加成功',
            type: 'success'
          });

          // 刷新父组件
          refresh();
        } catch (error) {
          if (error) {
            let msg: string = (error as Error).message;
            if (msg) {
              ElMessage({
                showClose: true,
                message: (error as Error).message,
                type: 'error'
              });
            }
          }
        } finally {
          isLoading.value = false;
        }
      } else {
        console.log('error submit!', invalidFields);
      }
    }
  );
};

// 组件实例
const addFormRef = ref<FormInstance>();
// 添加对象
const addForm = ref<AgentCreateDto>({
  displayName: '',
  isEnabled: true
});
</script>
<style scoped lang="scss">
.form-item-remark {
  width: calc(100% - 32px);
}

.form-item-input {
  width: 256px;
}
</style>